import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
import { withStyles } from 'material-ui/styles'
import { inject, observer } from 'mobx-react'
import Paper from 'material-ui/Paper';
import Helmet from 'react-helmet'

import style from './style'

import TopicsDetailStore from '../../stores/topic_detail'
import UserStore from '../../stores/user_store'

import TopicTips from '../topic_tips/index'
import tabs from '../../constant/tabs'
import dateFormat from '../../util/date_format'
import MoreMenu from '../more_menu/index'
import Comments from '../comments/index'
import LoadingStatus from '../loading_status/index'
import PostIcon from '../post_icon/index'
import CommentArea from '../comment_area/index'
// marked工具
import marked from '../../util/marked'

@inject((stores) => {
  const store = {
    topicDetail: stores.topicDetail,
    user: stores.user,
  }
  return store
})
@observer
class TopicDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isCollect: false,
      error: false,
    }
    this.collect = this.collect.bind(this)
    this.deCollect = this.deCollect.bind(this)
  }
  componentDidMount() {
    this.getTopicDetail()
  }
  // 获取话题详情
  getTopicDetail() {
    this.props.topicDetail.getTopicDetail(this.props.topicId).then(() => {
      this.checkIsCollect()
    }).catch(() => {
      this.setState({
        error: true,
      })
    })
  }
  // 收藏
  collect() {
    this.props.topicDetail.collect(this.props.topicId).then(() => {
      this.setState({
        isCollect: true,
      })
      this.props.user.getCollection(this.props.user.userInfo.loginName)
    }).catch((msg) => {
      if (msg) {
        alert(msg) //eslint-disable-line
      } else {
        alert('出错了，请稍后再试')
      }
    })
  }
  // 判断是否当前用户收藏的文章
  checkIsCollect() {
    const collection = this.props.user.collection.slice()
    const { topicId } = this.props
    collection.forEach((item) => {
      if (item.id === topicId) {
        this.setState({
          isCollect: true,
        })
        return true
      }
      return false
    })
  }
  // 取消收藏
  deCollect() {
    this.props.topicDetail.deCollect(this.props.topicId).then(() => {
      this.setState({
        isCollect: false,
      })
      this.props.user.getCollection(this.props.user.userInfo.loginName)
    }).catch((msg) => {
      if (msg) {
        alert(msg) //eslint-disable-line
      } else {
        alert('出错了，请稍后再试')
      }
    })
  }
  // 处理comments
  filterReplies(replies) {
    const { user } = this.props
    if (user.isLogin) {
      const userId = user.userInfo.id
      replies.forEach((reply) => {
        const { ups } = reply
        if (ups.indexOf(userId) !== -1) {
          reply.isUped = true
        } else {
          reply.isUped = false
        }
      })
    }

    return replies
  }
  asyncBootstrap() {
    return new Promise((resolve) => {
      this.props.topicDetail.getTopicDetail(this.props.topicId)
        .then(() => resolve(true))
        .catch(() => resolve(true))
    })
  }
  render() {
    const { topicDetail } = this.props.topicDetail
    const topic = topicDetail.get(this.props.topicId)
    const createAt = dateFormat(topicDetail.create_at, 'yyyy-mm-dd')
    const lastReplyAt = dateFormat(topicDetail.last_reply_at, 'yyyy-mm-dd')
    const { classes } = this.props
    return (
      <div className={classes.topicDetail}>
        { !this.state.error ?
          topic ?
            <div>
              <Helmet>
                <title>{topic.title}</title>
              </Helmet>
              <Paper className={classes.topicAuthor}>
                <div>
                  <div className={classes.avatar}>
                    <Link to={`/user/${topic.author.loginname}`}>
                      <img
                        className={classes.avatarImg}
                        src={topic.author.avatar_url}
                        alt={topic.author.loginname}
                      />
                    </Link>
                  </div>
                  <div className={classes.author}>
                    <span className={classes.nickName}>{topic.author.loginname}</span>
                    <span className={classes.createTime}>楼主 发表于：{createAt}</span>
                  </div>
                </div>
                <div className={classes.moreMenu}><MoreMenu /></div>
              </Paper>
              <Paper className={classes.paper}>
                <h1 className={classes.title}>{topic.title}</h1>
                <div className={classes.topicTips}>
                  <TopicTips
                    tab={tabs[topic.tab]}
                    lastReplyAt={lastReplyAt}
                    replyCount={topic.reply_count}
                    visitCount={topic.visit_count}
                    top={topic.top}
                    good={topic.good}
                  />
                  <div className={classes.tab}>
                    {tabs[topic.tab]}
                  </div>
                </div>
                <div
                  className={classes.content}
                  dangerouslySetInnerHTML={{ __html: marked(topic.content) }}
                />
              </Paper>
              <Paper>
                <Comments
                  comments={this.filterReplies(topic.replies)}
                  replyCount={topic.reply_count}
                />
              </Paper>
              <PostIcon />
              <CommentArea
                love={this.collect}
                deLove={this.deCollect}
                isCollect={this.state.isCollect}
                topicId={topic.id}
              />
            </div>
            :
            <LoadingStatus />
            :
            <div className={classes.error}>
              找不到该话题,话题可能已被删除...
            </div>
        }

      </div>
    )
  }
}

export default withStyles(style)(TopicDetail)

TopicDetail.propTypes = {
  classes: PropTypes.objectOf(Object),
  topicDetail: PropTypes.instanceOf(TopicsDetailStore),
  user: PropTypes.instanceOf(UserStore),
  topicId: PropTypes.string,
}
